
import struct
import packet_queue

GET_FILE_MESSAGE = 1
SEND_PACKET_MESSAGE = 2
GET_PACKETS_MESSAGE = 3


class GetFileMessage:
  def __init__(self,filename='',rate=0,packet_size=0):
    self.filename = filename
    self.rate = rate
    self.packet_size = packet_size
    
  def __str__(self):
    return "GetFile: {}, {}, {}".format(self.rate,self.packet_size,self.filename)
  
  def pack(self):
    out = struct.pack('HHH',GET_FILE_MESSAGE,self.rate,self.packet_size)
    out += self.filename
    return out
  
  def unpack(self,data):
    tmp,self.rate,self.packet_size = struct.unpack('HHH',data[:6])
    self.filename = data[6:]
    
    
class SendPacketMessage:
  def __init__(self,num_packets=0,packet_id=0,data=0):
    self.num_packets = num_packets
    self.packet_id = packet_id
    self.data = data
    
  def __str__(self):
    return "SendPacket: {} of {}, length: {}".format(self.packet_id+1,
                                              self.num_packets,
                                              len(self.data))
  def pack(self):
    out = struct.pack('HH',self.num_packets,self.packet_id)
    out += self.data
    return out
  
  def unpack(self,data):
    self.num_packets,self.packet_id = struct.unpack('HH',data[:4])
    self.data = data[4:]
  
  
class GetPacketsMessage:
  def __init__(self,queue=None):
    self.queue = queue
    
  def __str__(self):
    return "GetPackets: len:{}, {}".format(self.queue.size, self.queue)
  
  def pack(self):
    out = struct.pack('HH',GET_PACKETS_MESSAGE,self.queue.size)
    out += self.queue.pack()
    return out
  
  def unpack(self,data):
    tmp,size = struct.unpack('HH',data[:4])
    print 'size: ', size
    queue_in = packet_queue.Queue(size,0)
    queue_in.unpack(data[4:])
    print queue_in
    self.queue = queue_in
                                             
  
def get_message(data):
  message = None
  message_type, = struct.unpack('H',data[:2])
  if message_type == GET_FILE_MESSAGE:
    message = GetFileMessage()
  elif message_type == GET_PACKETS_MESSAGE:
    message = GetPacketsMessage()
  if message:
    message.unpack(data)
  
  return message